/*!
  @file storage_io.cpp
  @brief 
  @author Kyohei Otsu <kyon@ac.jaxa.jp>
  @date April, 2013
*/

#include <cstdio>

#include "png/libpng_helper.h"
#include "core/core.h"

using namespace std;

namespace png
{

bool PNG::readFromStorage(const std::string& filename, const png_byte color_mode)
{
  //-- open and png test
  FILE *fp = fopen(filename.c_str(), "rb");
  if (!fp) {
    ERROR("png file read failed: " << filename);
    return false;
  }
  png_byte header[8];
  fread(header, 1, 8, fp);
  if (png_sig_cmp(header, 0, 8)) {
    ERROR(filename << " is not a PNG file");
    return false;
  }

  int success = decode(fp, data_);

  fclose(fp);


  //-- color conversion
  if (success) {
    //TODO(kyohei)
  }

  return success;
}

bool PNG::writeToStorage(const std::string& filename, const png_byte color_mode) 
{
  if (!memory_alloced_) {
    INFO("image not loaded");
    return false;
  }

  //-- color conversion
  //TODO(kyohei)

  //-- file open
  FILE *fp = fopen(filename.c_str(), "wb");
  if (!fp) {
    ERROR("png file write failed");
    return false;
  }

  bool success = encode(data_, fp);

  fclose(fp);

  return success;
}

} // end of namespace
